<template>
    <view class="whole">
		<!--自定义头部-->
        <view class="header">
        	<view class="left" ><text  @click="confirmExit">取消</text></view>
        	<view class="center"><text>博客草稿</text></view>
        	<view class="right" @click="nextStep"><text>下一步</text></view>
        </view>
		<!--编辑器-->
		<view
		 class="editor-container">
		    <view class="editor-header">
		          <input 
		            type="text" 
		            v-model="blogTitle" 
		            placeholder="输入标题..." 
		            class="title-input"
		          />
		      </view>
			<editor
			   :adjust-position="false"
			    id="editor" 
			    class="ql-container" 
			    placeholder="开始输入..." 
			    show-img-size 
			    show-img-toolbar
			    show-img-resize 
			    @statuschange="onStatusChange" 
			    :read-only="readOnly" 
			    @ready="onEditorReady"
			    v-model="blogContent"
				@focus="isEditorFocused = true"
				 @blur="isEditorFocused = false"
			>
			</editor>
		</view>
		<!--底部工具栏-->
		<view class="toolbar"  @touchend.prevent  >
			        <view 
			            class="iconfont icon-tupian" 
			            :class="{ 'disabled': !isEditorFocused }"
			            @touchend.prevent="isEditorFocused ? handleClick('image') : showDisabledTip()">
			        </view>
			        <view 
			            class="iconfont icon-wenziyangshi" 
			            :class="{ 'disabled': !isEditorFocused ,
						  'active': activeIcon === 'textStyle'
						}"
			            @touchend.prevent="isEditorFocused ? handleClick('textStyle') : showDisabledTip()">
			        </view>
			        <view 
			            class="iconfont icon-fuwenben" 
			            :class="{ 'disabled': !isEditorFocused 
						, 'active': activeIcon === 'copy'
						}"
			            @touchend.prevent="isEditorFocused ? handleClick('copy') : showDisabledTip()">
			        </view>
			        <view 
			            class="iconfont icon-lianjie" 
			            :class="{ 'disabled': !isEditorFocused 
						}"
			            @touchend.prevent="isEditorFocused ? handleClick('link') : showDisabledTip()">
			        </view>
			        <view 
			            class="iconfont icon-chexiao" 
			            :class="{ 'disabled': !canUndo || !isEditorFocused }"
			            @touchend.prevent="isEditorFocused ? handleClick('undo') : showDisabledTip()">
			        </view>
			        <view 
			            class="iconfont icon-quxiaochexiao" 
			            :class="{ 'disabled': !canRedo || !isEditorFocused }"
			            @touchend.prevent="isEditorFocused ? handleClick('redo') : showDisabledTip()">
			        </view>
<!-- 
			<view class="iconfont icon-tupian" @touchend.prevent="handleClick('image')" ></view>
			<view :class="{'iconfont icon-wenziyangshi': true, 'active': activeIcon === 'textStyle'}" @touchend.prevent="handleClick('textStyle')"></view>
			<view :class="{'iconfont icon-fuwenben': true, 'active': activeIcon === 'copy'}" @touchend.prevent="handleClick('copy')"></view>
			<view class="iconfont icon-lianjie" @touchend.prevent="handleClick('link')"></view>
			<view class="iconfont icon-chexiao" @touchend.prevent="handleClick('undo')" :class="{ 'disabled': !canUndo }"></view>
			<view class="iconfont icon-quxiaochexiao" @touchend.prevent="handleClick('redo')"  :class="{ 'disabled': !canRedo }"></view>
				 -->		
		</view>
		<!--链接插入-->
		<!-- :style="{ bottom: keyboardHeight + 'px' }" -->
		 <view class="overlay" v-if="activeIcon === 'link'" @click="cancelInsert"  >
		    <view class="link-inserter"  @click.stop    >
		      <view class="link-header" @touchend.prevent>
		        <view class="left" ><text  @touchend.prevent="cancelInsert">取消</text></view>
		        <view class="center"><text>添加链接</text></view>
		        <view class="right" ><text @touchend.prevent="insertLink">添加</text></view>
		      </view>
		
		      <view class="link-input" >
		        <input
				id="linkTextInput"
		        v-model="linkText"
		        placeholder="链接文本"
		        class="link-text"
		        />
		        <input
				   id="linkUrlInput"
		          v-model="linkUrl"
		          placeholder="链接地址"
		          class="link-url"
		        />
		      </view>
		    </view>
		  </view>
		
		
		<!--文字样式-->
		<view class="textStyle" v-if="activeIcon === 'textStyle'" @touchend.prevent >
		    <view class="textFormat">
				<view class="text">文字格式</view>
				<view class="inconfonts">
					<image :class="formats.bold ? 'ql-active' : ''"   @touchend.prevent="format('bold')" class="iconfont icon-zitijiacu" ></image>
					<image :class="formats.italic ? 'ql-active' : ''"  @touchend.prevent="format('italic')" class="iconfont icon-zitixieti"></image>
					<image :class="formats.underline ? 'ql-active' : ''"  @touchend.prevent="format('underline')" class="iconfont icon-zitixiahuaxian"></image>
					<image :class="formats.strike ? 'ql-active' : ''"  @touchend.prevent="format('strike')"  class="iconfont icon-shanchuxian"></image>			 
				</view>
				
			</view>
			<view class="justification">
				<view class="text">对齐方式</view>
				<view class="inconfonts">
					 	<image :class="formats.align === 'left' ? 'ql-active' : ''" @touchend.prevent="format('align', 'left')" class="iconfont icon-wenziyangshi-zuoduiqi" ></image>
						<image :class="formats.align === 'center' ? 'ql-active' : ''" @touchend.prevent="format('align', 'center')" class="iconfont icon-wenziyangshi-juzhongduiqi" ></image>
						<image :class="formats.align === 'right' ? 'ql-active' : ''" @touchend.prevent="format('align', 'right')" class="iconfont icon-wenziyangshi-youduiqi" ></image>
						 <image :class="formats.align === 'justify' ? 'ql-active' : ''" @touchend.prevent="format('align', 'justify')" class="iconfont icon-H5bianjiqi-wenzi-yangshi-liangduanduiqi" ></image> 
				</view>
			</view>
		</view>
		
		
		<!--文字副本-->
		
		<view class="textTranscription" v-if="activeIcon === 'copy'" @touchend.prevent >
			<view class="firstLine">
				<view class="textTitle">
					<view class="text">标题</view>
					<view class="inconfonts">
						<image :class="formats.header === 1 ? 'ql-active' : ''" @touchend.prevent="format('header', 1)" class="iconfont icon-dabiaoti"></image>
						<image :class="formats.header === 2 ? 'ql-active' : ''" @touchend.prevent="format('header', 2)" class="iconfont icon-erjibiaoti"></image>
						<image :class="formats.header === 3 ? 'ql-active' : ''" @touchend.prevent="format('header', 3)" class="iconfont icon-sanjibiaoti"></image>		 
					</view>
				</view>
				
				<view class="textQuote">
					<view class="text">引用</view>
					<view class="inconfonts">
						 <image :class="formats.blockquote ? 'ql-active' : ''" @touchend.prevent="format('blockquote')" class="iconfont icon-yinyong"></image>		 
					</view>
				</view>
			</view>
			
			
			<!--第二行-->
			<view class="secondLine">
				<view class="textSort">
					<view class="text">排序</view>
					<view class="inconfonts">
						<image :class="formats.list === 'ordered' ? 'ql-active' : ''" @touchend.prevent="format('list','ordered')" class="iconfont icon-youxupaixu" ></image>
						<image :class="formats.list === 'bullet' ? 'ql-active' : ''" @touchend.prevent="format('list','bullet')" class="iconfont icon-wuxupaixu" ></image>		 
					</view>
				</view>
				
				<view class="textSegmentation">
					<view class="text">分割</view>
					<view class="inconfonts">
						<image  @touchend.prevent="insertDivider"  class="iconfont icon-fengexian" ></image>		 
					</view>
				</view>
			</view>
		</view>
		
		
		
		
    </view>
</template>

<script>
import request from "../../utils/request.js";
import file from "../../utils/file.js";
export default {
    data() {
        return {
			imgRegex:/<img[^>]*\s+src="([^"]*)"\s+[^>]*data-custom="storageFileName=([^"]*)"/g,
			blogTitle:'',
			blogContent: undefined,
			readOnly: false,
			editorInstance:null,
			formats:{},
		    activeIcon: null, // 当前工具栏激活的图标
			history: [], /*撤销和取消撤销是否可用*/
			redoStack: [],
			canUndo: false,
			canRedo: false,
			isEditorFocused: false,//富文本编辑器是否获得焦点
			//linkInputFocused:false,//link-input不需要改变整个页面高度
			linkText:'',
			linkUrl:'',
			userId:undefined,
			token:undefined,
			//tepPostId:'',
			 draftId:'',
			resourceId:-1,
			imgFileName:[],
			imgMap:{},
			requested:false
        };
    },
	 watch: {
	    // 监听 blogContent 变化，获取新旧内容进行对比
	    blogContent(newContent, oldContent) {
			console.log("内容变化");
	      this.detectImageDeletion(newContent, oldContent);
	    }
	  },
	mounted() {
		 // 监听键盘高度变化
		
	},
	onLoad(options) {
	         // 接收传入的草稿ID（draftId）和资源ID（resourceId）
	            const draftId = options.draftId; // 草稿ID
	            const resourceId = options.resourceId; // 资源ID
	            let requested=false;
	            // 获取用户ID和token
	            this.userId = uni.getStorageSync("UID");
	            this.token = uni.getStorageSync("token");
				//用户是否登录成功
				// console.log("用户id---token",this.userId,this.token,this.userId || this.token);
				if(!this.userId || !this.token){
					 uni.showToast({
					    title: '还未登录',
					    icon: 'error',
					    duration: 1000 // 设置显示的时长，单位是毫秒，2000ms = 2秒
					  });
					  // 2秒后执行跳转
					  setTimeout(() => {
					    uni.redirectTo({
					      url: "/pages/login/login"
					    });
					  }, 1000); // 等待2秒后跳转到登录页面
				}
	            // 处理草稿ID：如果没有传入草稿ID，则生成一个新的草稿ID
	            if (!draftId) {
	                this.draftId = this.generateDraftId();
	            } else {
	                this.draftId = draftId;
					this.requested=true;
	            }
	            // 处理资源ID：如果没有传入资源ID，则设置为null或默认值
	          if(resourceId){
				  this.resourceId=parseInt(resourceId);
				  if(this.resourceId!=-1){
				  this.requested=true;
				  }
			  }

			 
	            console.log('接收到的草稿ID:', this.draftId);
	            console.log('接收到的资源ID:', this.resourceId);
	            
	 },
	async mounted() {
	 	// this.$nextTick(() => {
	 	//    // 页面渲染完毕后发送请求
	 	  
		   
	 	//  });
		if (this.requested) {
		 await this.fetchDraftData(this.draftId, this.userId, this.resourceId);
		}
	 },
	methods:{
		async  loadImage(fileName) {
			console.log(fileName);  // 输出 "1.jpg", "2.jpg" 等
			const url = `${this.baseUrl}/file/${this.draftId}?type=tempPostImg&fileName=${fileName}`;
			//console.log("请求的图片路径:", url);
			let result=await request.sendUniGetRequestByNetWork(this.userId,this.token,url);
			console.log("图片请求的数据:",result);
			if(result){
				if(result.code===1){
					let imgResult=result.data;
					if(imgResult){
						if(imgResult.imgType && imgResult.fileContent){
							const src=file.generateImagUrl(imgResult.fileContent,imgResult.imgType);
							const key = `${this.draftId}_${fileName}`;
							this.imgFileName.push(key);
							//this.imgMap[key] = src;
							// this.replaceImageSrcInHtml()
							// 返回 key 和 src
							 return { key, src };
						}
					}
				}
			}
			  return null;
		     },
			 getLastPart(fileName) {
			   // 查找最后一个下划线的位置
			   const lastUnderscoreIndex = fileName.lastIndexOf('_');
			   
			   // 获取从下划线后的部分并去掉前面的 '_'
			   const lastPart = fileName.substring(lastUnderscoreIndex + 1);
			 
			   return lastPart;  // 返回结果 "1.jpg"
			 },
		async fetchDraftData(draftId,userId, resourceId) {
			try {
			 let data={
				draftId:draftId,
				 userId:userId,
				 resourceId:resourceId
			 }
			 console.log(data);
			  let result=await request.sendUniPostRequestByNetWork(this.userId,this.token,"searchDraft",data,"/draft/searchDraft");
			  console.log("加载的页面数据",result);
			   if(result){
				   if(result.code===1){
				   	const data=result.data;
				   	  if (data && data.title && data.content) {
				   	    this.blogTitle= data.title ;
						 // this.editorInstance.setContents({
						 //    html:data.content
						 // });
						 // text:data.content ,
						 // type: 'html'
						 try{
							// console.log("原始html",data.content);
							 //await  this.getEditorHtml();
							 const html=data.content;
							 console.log("鉴定html",html);
							 const currentImages = this.extractImages(html);
							 console.log("查找图片",currentImages);
							
							//   for (const item of currentImages) {
							//    // 提取storageFileName
							//    const storageFileName = item.storageFileName;
							//    // 获取最后的"数字.文件后缀"部分
							//    const lastPart = storageFileName.slice(storageFileName.lastIndexOf('_') + 1);
							//    // this.loadImage(lastPart);
							//    const result = await this.loadImage(lastPart);
							//      if (result) {
							//            const { key, src } = result;
							//            console.log("生成的图片 key:", key);
									   
							//          //  console.log("生成的图片 src:", src);
							// 		 newHtml= this.replaceImageSrcInHtml(newHtml,key,src);
									  
							//            // 在此处可以使用 key 和 src 进行其他操作
							//        } else {
							//            console.log("图片加载失败或没有有效的数据");
							//        }
							// }
							 // 1. 创建一个数组来存储所有图片的替换数据
							    const imageReplaceData = [];
							  const loadImagePromises = currentImages.map(async (item) => {
							         const storageFileName = item.storageFileName;
							         const lastPart = storageFileName.slice(storageFileName.lastIndexOf('_') + 1);
							         
							         // 异步加载图片
							         const result = await this.loadImage(lastPart);
							         if (result) {
							             const { key, src } = result;
							             console.log("生成的图片 key:", key);
										   // 3. 收集替换数据
										 imageReplaceData.push({ key, src });
							             // 替换 HTML 中的图片 src
							            // newHtml = this.replaceImageSrcInHtml(newHtml, key, src);
							         } else {
							             console.log("图片加载失败或没有有效的数据");
							         }
							     });
							 
							     // 等待所有图片加载完成
							await Promise.all(loadImagePromises);
							 console.log("替换的src的键为:",this.imgFileName);
							// console.log("新的html: ",newHtml);
							// 4. 所有图片加载完成后进行替换
							// 4. 所有图片加载完成后进行替换
							console.log("key --- value",imageReplaceData);
							   let newHtml=this.replaceImageSrcInHtml(html,imageReplaceData);
							    // imageReplaceData.forEach(({ key, src }) => {
							    //     newHtml = this.replaceImageSrcInHtml(newHtml, key, src);
							    // });
								
							console.log("op")
							 //替换html
							 this.editorInstance.setContents({
							    html:newHtml
							 });
							 
							
						 }catch (error) {
							console.error('获取编辑器内容失败:', error);
						}
						return;
				   	 } 
				   }
			   }
			   uni.showToast({
			         title: '数据请求失败',
			         icon: 'none'
			      });
			} catch (error) {
			  console.error("搜索请求失败:", error);
			  uni.showToast({
			        title: '请求错误',
			        icon: 'none'
			     });
			} 
			 
		 },
		 
	    async nextStep() {
			if(this.blogTitle.length<5 || this.blogTitle.length>100){
				uni.showToast({
				  title: '标题要在5-100个字之间',
				  icon: 'none',
				  duration: 1500
				});
				return;
			}
			let blogHtml=await this.getEditorHtml();
			blogHtml=this.replaceAllSrcInHtml(blogHtml);
			blogHtml = blogHtml.trim(); // trim() 会去除两端的空格和换行符
			let blogText=await this.getEditorText();
			blogText=blogText.trim();
			//传递imgFileName  tepPostId  blogContent中的html blogTitle
		  uni.navigateTo({
		    url: `/pages/blogNextStep/blogNextStep?blogTitle=${encodeURIComponent(this.blogTitle)}&imgFileName=${encodeURIComponent(this.imgFileName)}&draftId=${this.draftId}&blogContent=${blogHtml}
			&resourceId=${encodeURIComponent(this.resourceId)}&blogText=${encodeURIComponent(blogText)}
			`
		  });
		},
	  confirmExit() {
		      uni.showModal({
		        title: '提示',
		        content: '您有未保存的更改，是否要保存？',
		        success: (res) => {
		          if (res.confirm) {
		            // 用户选择保存
		            this.saveChanges();
					//console.log(this.blogContent);
		          } else if (res.cancel) {
		            // 用户选择不保存
		            this.exitWithoutSaving();
		          }
		        }
		      });
		 },
		async saveChanges() { 
			  try {
				  let html=await this.getEditorHtml();
				   let text =await this.getEditorText();
				   console.log("内容",html);
				  if (this.blogTitle.trim().length === 0 && text.trim().length === 0 &&html==='<p><br></p>') {
				    // uni.switchTab({
				    //   url: '/pages/index/index' // 跳转到 tabBar 页面
				    // });
					uni.navigateBack()
				    return;
				  }
				  // 显示加载
				  uni.showLoading({
				    title: '保存中...',   // 显示的文字
				    mask: true           // 是否显示透明蒙层，防止触摸
				  });
				  
				   html=this.replaceAllSrcInHtml(html);
				  // console.log("保存的html",html);
				  let data={
				  	draftId:this.draftId,
				  	userId:this.userId,
				    resourceId:this.resourceId,
					title:this.blogTitle,
					content:html,
					coverOption:'',
					articleType:'original',
					originalUrl:'',
					saveedTags:[],
					description:'',
					//type:"saveAll"
					type:"saveTitleAndContent",
				  }
				  console.log(data);
				   let result=await request.sendUniPostRequestByNetWork(this.userId,this.token,"saveDraft",data,"/draft/saveDraft");
				   
				   console.log(result);
				   if(result){
					   if(result.code===1){
						   // 保存更改的逻辑
						   uni.showToast({
						     title: '更改已保存！',
						     icon: 'success',
							 duration:1000
						   });
						   setTimeout(() => {
						     // uni.switchTab({
						     //    url: '/pages/index/index' // 跳转到 tabBar 页面
						     //  });
							  uni.navigateBack();
						   }, 1000); // 等待2秒后跳转到登录页面
						  
						   return;
						 }
				   	}
				   uni.showToast({
				     title: '保存失败',
				     icon: 'none'
				   });
				}catch (error) {
					uni.showToast({
					  title: '保存失败',
					  icon: 'none'
					});
					console.error('保存失败:', error);
				}finally{
					// 隐藏加载
					uni.hideLoading();
				}
				
		     },
		     exitWithoutSaving() {
		       // 不保存时的逻辑
		       uni.showToast({
		         title: '已放弃更改，正在退出...',
		         icon: 'none'
		       });
		       // 可以在这里添加跳转或其他逻辑
			     setTimeout(() => {
			           // uni.switchTab({
			           //    url: '/pages/index/index' // 跳转到 tabBar 页面
			           //  });
					    uni.navigateBack();
			        }, 500); // 2000毫秒（2秒）后返回
		   },
		showDisabledTip() {
		    uni.showToast({
		        title: '请先聚焦编辑器',
		        icon: 'none',
		        duration: 1000 // 显示1秒
		    });
		},
		onStatusChange(status) {
		    console.log('编辑器状态变化:', status);
			const formats = status.detail;
			this.formats = formats;
		},
		onEditorReady(editorInstance) {
		    console.log('编辑器准备就绪');
			uni.createSelectorQuery().in(this).select('.ql-container').fields({
			      context:true
			  },res=>{
			       this.editorInstance= res.context;
			 }).exec()	 
			
		},
		format( style,value) {
		    console.log(`格式化样式: ${style}, 值: ${value}`);
		    if (this.editorInstance) {
				if (style === 'align' || style==='header' || style==='list') {
				    this.editorInstance.format(style, value); // 对齐方式
				} else {
				    this.editorInstance.format(style, true); // 其他格式
				}
		       this.addToHistory(this.blogContent); // 每次状态变化时添加到历史
		    }
		},
		 handleClick(icon) {
			 if(this.activeIcon === icon && (this.activeIcon === 'textStyle' || this.activeIcon === 'copy' || this.activeIcon === 'link' )){
				 this.activeIcon=null;
				 return;
			 }
		     this.activeIcon = icon; // 设置当前激活的图标
			 if(icon==='image'){
				 this.chooseImageAndUpload();
			 }else if(icon==='undo'){
				 this.undo();
			 }else if(icon==='redo'){
				 this.redo();
			 }else if(icon==='link'){
				// this.insertLink();
			 }
		 },
		 addToHistory(content) {
		    this.history.push(content);
		    this.redoStack = []; // 清空重做栈
		    this.canUndo = true;
		    this.canRedo = false; // 重做不可用
		},
		 undo() {
			 if (this.canUndo) {
			    const lastAction = this.history.pop();
			    this.redoStack.push(lastAction);
			    this.updateCanUndoRedo();
				this.editorInstance.undo();
			}
			 
		 },
		 redo() {
			 if (this.canRedo) {
			    const lastRedoAction = this.redoStack.pop();
			    this.history.push(lastRedoAction);
			    this.updateCanUndoRedo();
			    this.editorInstance.redo();          
			 }
		 },
		 updateCanUndoRedo() {
		    this.canUndo = this.history.length > 0;
		    this.canRedo = this.redoStack.length > 0;
		},
		 //插入分割线
		insertDivider(){
			this.editorInstance.insertDivider({
				success: function() {
					this.addToHistory(this.blogContent); // 每次状态变化时添加到历史
					console.log('insert divider success')
				}
			})
		},
		insertImage() {
			uni.showLoading({
			    title:'loading...'
			})
			uni.chooseImage({
					sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
					sourceType: ['album'], // 从相册选择
			       success:res=>{
			           for(let i=0;i<res.tempFilePaths.length;i++){
			               this.editorInstance.insertImage({
							   src:res.tempFilePaths[i],
							    style: 'margin-top: 50px; margin-bottom: 50px;'
			               })
			           }
					   this.addToHistory(this.blogContent); // 每次状态变化时添加到历史
			       },
					fail() {
						
					},complete() {
						 uni.hideLoading()
						 return;
					}
			   })
				uni.hideLoading();
		},
		//插入链接
		insertLink() {
			if (this.linkText && this.isValidUrl(this.linkUrl)) {
			  // 插入链接的逻辑
			  const linkHtml = `<a href="${this.link}" target="_blank" rel="noopener noreferrer">${this.linkText}</a>`;
			    this.editorInstance.insertText({
			        text: linkHtml,
			        type: 'html'
			    });
			  console.log('链接已插入:', this.linkText, this.linkUrl);
			  this.resetInputs();
			  this.cancelInsert();
			} else {
			  uni.showToast({
			    title: '请输入有效的链接文本和URL。',
			    icon: 'none'
			  });
			}
			
		},
		cancelInsert() {
		    this.resetInputs();
		    this.activeIcon = null; // 隐藏链接插入器
		},
		resetInputs() {
		  this.linkText = '';
		  this.linkUrl = '';
		},
		isValidUrl(url) {
		  const pattern = new RegExp('^(https?:\\/\\/)?'+ // 协议
		    '((([a-z\\d]([a-z\\d-]*[a-z\\d])?)\\.)+[a-z]{2,}|' + // 域名
		    'localhost|' + // localhost
		    '\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}|' + // ipv4
		    '\\[?[a-fA-F\\d]*:[a-fA-F\\d:]+\\]?)' + // ipv6
		    '(\\:\\d+)?(\\/[-a-z\\d%_.~+]*)*' + // 端口和路径
		    '(\\?[;&a-z\\d%_.~+=-]*)?' + // 查询字符串
		    '(\\#[-a-z\\d_]*)?$','i'); // 片段标识符
		  return !!pattern.test(url);
		},
		focusInput(inputId) {
			
		},
		//临时postId
		 generateDraftId() {
		            const timestamp = Date.now(); // 当前时间戳
		            const randomPart = Math.floor(Math.random() * 1000); // 生成随机数
		            const draftId = `${timestamp}_${this.userId}_${randomPart}`;
		            return draftId;
		    },
		//选择图片
		 chooseImage() {
		  return new Promise((resolve, reject) => {
		    uni.chooseImage({
		      count: 9, // 默认选择的图片数量
		      sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图
		      sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机
		      success: (res) => {
		        const tempFilePaths = res.tempFilePaths;
		        resolve(tempFilePaths);
		      },
		      fail: (err) => {
		        reject(err);
		      }
		    });
		  });
		},
		// 上传单张图片，支持传递自定义的 URL、数据和头部
		uploadImage(filePath, url, data = {}, header = {}) {
		  return new Promise((resolve, reject) => {
		    uni.uploadFile({
		      url: url, // 使用传入的 URL
		      filePath: filePath,
		      name: 'file', // 后端接收文件的字段名
		      formData: {
		        ...data // 扩展其他额外的数据
		      },
		      header: {
		        ...header // 扩展自定义的头部
		      },
		      success: (res) => {
		        try {
		          const resultData = JSON.parse(res.data); // 假设服务器返回的结果是 JSON 格式
		          resolve(resultData); // 返回上传成功的数据
		        } catch (error) {
		          reject('解析返回数据失败'); // 解析失败处理
		        }
		      },
		      fail: (err) => {
		        reject(err); // 上传失败处理
		      }
		    });
		  });
		},
		uploadImages(images, url, data = {}, header = {}) {
		  // 使用 map 遍历每个图片，并将索引传递到 data 中
		  const uploadPromises = images.map((image, index) => {
		    // 在上传时给 data 添加一个新的属性，表示是第几张图片
		    const updatedData = { ...data, imageIndex: index + 1 }; // imageIndex 为图片的索引，从 1 开始
		    return this.uploadImage(image, url, updatedData, header);
		  });
		
		  return Promise.all(uploadPromises) // 返回所有上传的结果
		    .then(results => {
		      // 所有图片上传成功后的处理
		      return results; // 返回所有上传成功的结果
		    })
		    .catch(err => {
		      // 处理上传失败的情况
		      console.error('上传失败:', err);
		      throw err; // 抛出错误以便外部捕获
		    });
		},
		//选择图片并上传
		async chooseImageAndUpload() {
		  try {
		    const tempFilePaths = await this.chooseImage();
			uni.showLoading({
			    title:'加载中'
			})
		   const url = this.baseUrl+"/file/upload"; // 自定义上传的 URL
		   console.log(this.draftId);
		     const data = {
		       userId: this.userId,
			   signId:this.draftId,
			   type:'tempPostImg'
		     };
			 const header = {
			    uid:this.userId,
				token:this.token
			   };
		    const uploadedImages = await this.uploadImages(tempFilePaths, url, data,header);
		    // 处理上传成功的图片 URL
		    
			  // 遍历 uploadedImages，根据 imageIndex 找到对应的占位符并替换为图片 URL
			uploadedImages.forEach(result => {
				if(result){
					console.log('成功上传的图片:', result);
					if(result.code===1){
						const imageData=result.data;
						if(imageData.imageIndex && imageData.storageFileName ){
							console.log(imageData.imageIndex, imageData.storageFileName);
							 // 将 imageIndex 转换为数字
							 const imageIndex = parseInt(imageData.imageIndex, 10);
							
							   // 确保索引有效
							if (!isNaN(imageIndex) && imageIndex-1 >= 0 && imageIndex-1 < tempFilePaths.length) {
							    // 找到对应的 tempFilePaths 中的 URL
							    const imageUrl = tempFilePaths[imageIndex-1];
							    // 将图片插入到编辑器中
							    this.insertImageToEditor(imageUrl, this.draftId+'_'+imageData.storageFileName);
								this.imgFileName.push( this.draftId+'_' + imageData.storageFileName);
							} else {
							    console.warn('第imageIndex张:', imageData.imageIndex);
							}
						}
					}else{
						if(result.msg){
							const imageData=result.data;
							if(imageData){
								if(imageData.imageIndex ){
									const error = "第"+imageData.imageIndex+"张图片"+result.msg;
								 uni.showToast({
								        title:error , // 使用 result.msg 作为提示信息
								        icon: 'none', // 使用 'none' 图标
								        duration: 2000 // 持续时间
								});
								return;
								}
							}
							uni.showToast({
							        title:result.msg, // 使用 result.msg 作为提示信息
							        icon: 'none', // 使用 'none' 图标
							        duration: 2000 // 持续时间
							});
						}
						
					}
				}
			  // 你需要确保占位符的 selector 里有正确的 `data-index` 属性来匹配 imageIndex
			  //this.insertImageIntoEditor(imageData.imageIndex, imageData.imageUrl);
			});
		    //return uploadedData; // 返回上传成功的数据
		  } catch (error) {
		    throw error; // 抛出错误以便外部捕获
		  }finally{
			  uni.hideLoading();
		  }
		},
		    // 获取编辑器 HTML 内容并提取图片
		    getEditorHtml() {
		      return new Promise((resolve, reject) => {
		        this.editorInstance.getContents({
		          success: (res) => {
		            // 获取 HTML 内容
		            const htmlContent = res.html;
		            //console.log('HTML 内容:', htmlContent);
		            // 返回 HTML 内容
		            resolve(htmlContent); // 返回 HTML 内容
		          },
		          fail: (error) => {
		            console.log('获取编辑器内容失败:', error);
		            reject(error); // 失败时返回错误
		          },
		          complete: () => {
		            console.log('接口调用结束');
		          }
		        });
		      });
		    },
			getEditorText() {
			  return new Promise((resolve, reject) => {
			    this.editorInstance.getContents({
			      success: (res) => {
			        // 获取 HTML 内容
			        const text = res.text;
			        //console.log('HTML 内容:', htmlContent);
			        // 返回 HTML 内容
			        resolve(text); // 返回 HTML 内容
			      },
			      fail: (error) => {
			        console.log('获取编辑器text失败:', error);
			        reject(error); // 失败时返回错误
			      },
			      complete: () => {
			        console.log('接口调用结束');
			      }
			    });
			  });
			},
		// 假设这是你用来将图片插入到编辑器中的方法
		insertImageToEditor(imageUrl, storageFileName) {
		    // 插入图片前可以先打印出来图片URL和标识
		    console.log('插入图片:', imageUrl, '作为标识:', storageFileName);
		    
		    // 具体插入图片的逻辑
		   const image= this.editorInstance.insertImage({
		        src: imageUrl,
		        alt: '图片',    // 替代文本，图片加载失败时显示
		        width: '100%',   // 设置图片宽度
		        height: 'auto',  // 高度自动，根据宽度调整
		        extClass: 'my-custom-image-class',  // 添加自定义的CSS类
		        data: { storageFileName: storageFileName }  // 将标识存储在图片的data属性中
		    });
			
			    //设置自定义的data-storagefilename属性
			    const imageElement = image;
			    if (imageElement) {
			        imageElement.setAttribute('data-storagefilename', storageFileName);  // 在图片上添加自定义属性
			    }
		},
		   // 检测图片删除
		   detectImageDeletion(newContent, oldContent) {
		       // 提取旧内容和新内容中的图片
			   let prevImages = [];  // 使用 let 以便在后续修改
			       if (oldContent ) {
			           prevImages = this.extractImages(oldContent.detail.html);
			       }
		       const currentImages = this.extractImages(newContent.detail.html);
		  //  console.log(prevImages,currentImages);
		       // 判断是否有图片被删除
		        // 判断是否有图片被删除
		           const deletedImages = prevImages.filter(prevImg => 
		               !currentImages.some(currImg => currImg.src === prevImg.src && currImg.storageFileName === prevImg.storageFileName)
		           );
		       if (deletedImages.length > 0) {
		           console.log('图片已删除:', deletedImages);
		          // this.handleImageDelete(deletedImages, oldContent); // 执行图片删除后的处理逻辑
				  this.removeDeletedImagesFromFileName(deletedImages);
		       }
		   
		       // 更新 previousContent
		      // this.previousContent = newContent;
		   },
		   replaceImageSrcInHtml(html, replacements) {
			   console.log("替换所有的src为为指定src");
		       // 正则表达式：匹配 img 标签，获取 src 和 data-custom 中的 storageFileName
		       const imgRegex = this.imgRegex;
		       let match;
		   
		       console.log("传入替换的key-value:", replacements); // 输出所有需要替换的 key-value 对
		   
		       // 遍历所有匹配的 img 标签
		       while ((match = imgRegex.exec(html)) !== null) {
		           const currentSrc = match[1]; // 获取当前 src
		           const storageFileName = match[2]; // 获取 storageFileName
		           console.log("当前匹配的图片：", match[0]);
		           // console.log("当前图片的 src:", currentSrc);
		            console.log("当前图片的 storageFileName:", storageFileName);
		   
		           // 遍历 replacements 数组，检查是否存在对应的 storageFileName
		           for (let i = 0; i < replacements.length; i++) {
		              // const { storageFileName: replacementFileName, newSrc } = replacements[i];
					  // console.log(replacements[i]);
					   const key=replacements[i].key;
					   const newSrc=replacements[i].src;
		               // 如果 storageFileName 匹配，就替换 src
		               if (storageFileName === key) {
		                 //  console.log("替换 src:", currentSrc);
		   
		                   // 替换 img 标签中的 src
		                   html = html.replace(match[0], match[0].replace(`src="${currentSrc}"`, `src="${newSrc}"`));
		               }
		           }
		       }
		   
		       // 返回替换后的 html
		       return html;
		   },
		//  replaceImageSrcInHtml(html, key, src) {
		//     // 正则表达式：匹配 img 标签，获取 src 和 data-custom 中的 storageFileName
		//     const imgRegex = this.imgRegex;
		//     let match;
		//     console.log("传入替换的key值:",key);
		//     // 遍历所有匹配的 img 标签
		//     while ((match = imgRegex.exec(html)) !== null) {
		//         const storageFileName = match[2]; // 获取 storageFileName
		// 		// console.log("替换的匹配1: ",match[0]);
		// 		// console.log("替换的匹配2: ",match[1]);
		// 		 console.log("替换的匹配3: ",match[2]);
		//         // 如果传入的 key 等于 storageFileName，则进行替换
		//         if (storageFileName === key) {
		//            // console.log(`找到匹配的图片，当前 src: ${match[1]}, 需要替换为 src: ${src}`);
		//             // 用新的 src 替换原有的 src
		//             html = html.replace(match[0], match[0].replace(`src="${match[1]}"`, `src="${src}"`));
		//             console.log(`替换后的 img 标签: ${match[0]}`);
		// 			break;
		//         }
		//     }
		
		//     // 返回替换后的 html
		//     return html;
		// },
		 //把所有匹配的src 变为空字符串
		replaceAllSrcInHtml(html) {
			console.log("替换所有的src为空");
		    // 正则表达式：匹配 img 标签的 src 和 data-custom 中的 storageFileName /<img[^>]*src="([^"]*)".*data-custom="storageFileName=([^"]+)"/g
		    const imgRegex = this.imgRegex;
		    let match;
		    let newHtml=html;
		    // 遍历所有匹配的 img 标签
		    while ((match = imgRegex.exec(html)) !== null) {
				const newSrc="";
		        const currentSrc = match[1]; // 获取当前 src
		        const storageFileName = match[2]; // 获取 storageFileName
			   // console.log("匹配的 math0",match[0]);
				//console.log("匹配的 math1",match[1]);
		        console.log("匹配的 storageFileName:", storageFileName);
				console.log("要修改的匹配标签:", match[0].replace(`src="${currentSrc}"`, `src="${newSrc}"`));
		        // 如果当前的 src 不为空字符串，则将其替换为空字符串
		           newHtml = newHtml.replace(match[0], match[0].replace(`src="${currentSrc}"`, `src="${newSrc}"`));
				 //  console.log("中间新的html: ",newHtml)
		          //  console.log(`已替换图片 src 为空: ${storageFileName}`);
		        
		    }
			console.log("最总替换后的html",newHtml);
		    // 返回替换后的 html
		    return newHtml;
		},
		   // 从 HTML 内容中提取所有的图片 src 和 storageFileName
		  extractImages(html) {
		      //console.log(html);
		      const images = [];
			 // const imgRegex = /<img[^>]*src="([^"]*)".*data-custom="storageFileName=([^"]+)".*data-local="([^"]*)"/g;
		      // 正则表达式：匹配 img 标签的 src 和 data-custom 属性中的 storageFileName
		      const imgRegex = this.imgRegex; 
		      let match;
		      while ((match = imgRegex.exec(html)) !== null) {
		          // 提取图片的 src 和 storageFileName
		          images.push({
		              src: match[1],                  // 图片的 src
		              storageFileName: match[2]       // 提取出来的 storageFileName
		          });
		      }
		      return images;
		  },
		  removeDeletedImagesFromFileName(deletedImages) {
		      deletedImages.forEach(deletedImage => {
		          const index = this.imgFileName.indexOf(deletedImage.storageFileName);
		          if (index !== -1) {
		              // 删除 imgFileName 数组中的相应项
		             this.imgFileName.splice(index, 1);
		              console.log(`已删除: ${deletedImage.storageFileName} 从 imgFileName 数组`);
		          }
		      });
		      console.log('更新后的 imgFileName:', this.imgFileName);
		  }
		
		
	}
}
</script>



<style lang="scss">
.whole {
    display: flex;
    flex-direction: column;
    height: 100%;
    background-color: #f0f0f0;
    overflow: hidden;
}
.my-custom-image-class {
	//width: 400rpx;
	height: auto;
    display: block;  /* 将图片转换为块级元素 */
    margin-left: auto; /* 左右自动边距，配合 `margin-right: auto` 实现居中 */
    margin-right: auto;
}
.header{
	padding-top: var(--status-bar-height);
	z-index: 9999;
	font-size: 1.2rem;
	height: 100rpx;
	width: 100%;
	background-color: #f0f0f0;
	position: sticky;
	top: 0;
	//padding: 10rpx;
	display: flex;
	justify-content: space-between; /* 左右两侧均匀分布 */
	align-items: center;
	 border-bottom:1rpx solid  #ccc;
	 .left, .center, .right {
	     flex: 1; /* 每个部分占据相等的空间 */
	     text-align: center; /* 文本居中 */
	 }
	 
	 .left {
		 margin-left: 20rpx;
	     text-align: left; /* 左侧文本左对齐 */
	 }
	 
	 .right {
		 margin-right: 20rpx;
	     text-align: right; /* 右侧文本右对齐 */
	 }
	 
	 .text {
	     font-size: 16px; /* 字体大小 */
	     color: #333; /* 字体颜色 */
	     cursor: pointer; /* 鼠标悬停时显示手指光标 */
	 }
	 
	 .text:hover {
	     color: #007bff; /* 悬停时改变颜色 */
	 }
}
/*编辑器的样式*/
.editor-container{
    background-color: #f8f8f8; /* 背景颜色 */
	//background-color: #007bff;
	flex: 1;
	display: flex;
	flex-direction: column;
	 overflow: hidden; /* 防止不必要的滚动 */
	.editor-header {
	 height: 60rpx;
	box-sizing: border-box;
	background-color: #f8f8f8; /* 背景颜色 */
	border-bottom:1rpx solid  #ccc;
	  
	}
	.title-input {
	  padding-left: 20rpx;
	 // background-color: #f0f0f0;
	  width: 100%; /* 输入框宽度 */
	  height: 100%;
	}
	.ql-container {
		background-color: #f0f0f0;
		padding: 20rpx;
	    box-sizing: border-box;
	    width: 100%;
		flex: 1;
		overflow-y: auto; /* 允许内容滚动 */
	    line-height: 1.5;
	}
}

/*底部工具栏*/
.toolbar {
    display: flex;
    justify-content: space-around;
    align-items: center;
	height: 120rpx;
    background-color: #f8f8f8; /* 背景颜色 */
    border-top: 1rpx solid #ddd;
	.iconfont{
		line-height: 50rpx;
		text-align: center;
		width: 50rpx; /* 图标宽度 */
		height: 50rpx; /* 图标高度 */
		font-size: 50rpx;
		color: black; /* 正常状态为黑色 */
	}
	.iconfont.disabled {
	    color: lightgray; /* 灰淡色 */
	    pointer-events: none; /* 禁止点击 */
	}
	.active {
	  color: orange; /* 激活状态的颜色 */
	}
}
.active {
    color: orange; /* 激活状态为橙色 */
}


/*文本样式*/
.textStyle {
	background-color: #f0f0f0;
   display: flex;
   flex-direction: column;
  .textFormat, .justification {
	display: flex;
	flex-direction: column;
	background-color: white;
  }
  .text{
	 color: #ccc; 
	 padding-left: 20rpx;
	 
  }
  .inconfonts {
	background-color: #f0f0f0;
    display: flex;
	height: 100rpx;
    justify-content: space-around;
     align-items: center;
	.iconfont{
	line-height: 50rpx;
	text-align: center;
	width: 50rpx; /* 图标宽度 */
	height: 50rpx; /* 图标高度 */
	font-size: 50rpx;
	color: #ccc; /* 正常状态为黑色 */
	}
	.ql-active {
	color: #06c;
	}
  }
}



/*文字副本*/
.textTranscription {
    background-color: #fff;
    padding: 20rpx;
    border-radius: 10rpx;
    box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
	display: flex;
	flex-direction: column;
	.firstLine, .secondLine {
		//background-color: #007bff;
	    display: flex;
		align-items: center;
		justify-content: space-between;
	    //margin-bottom: 15rpx; /* 增加行间距 */
		.textTitle, .textSort, .textQuote, .textSegmentation {
		    //flex: 1;
		    margin-right: 10rpx; /* 右侧间距 */
			.text {
			    font-size: 28rpx;
				color: #ccc; 
				
			   
			    margin-bottom: 5rpx;
			}
			
			.inconfonts {
				background-color: #ddd;
			    display: flex;
			    justify-content: space-around;
			    align-items: center;
				.iconfont {
				    width: 50rpx;
				    height: 50rpx;
				    line-height: 50rpx;
				    text-align: center;
				    font-size: 50rpx;
				    color: #999; /* 默认状态为灰色 */
				    transition: color 0.3s; /* 过渡效果 */
				}
				.ql-active {
				 color: #06c;
				}
			}
			
		}
		.textTitle, .textSort{
			//background-color: #ddd;
			padding: 20rpx;
			width: 60%;
		}
		.textQuote, .textSegmentation {
			padding: 20rpx;
			flex: 1;
		}
		
	}
}
.overlay {
  position: fixed;
  height: 100vh;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5); /* 半透明背景 */
  display: flex;
  justify-content: center;
  align-items: flex-end; /* 将内容放在底部 */
   z-index: 10000;
  .link-inserter {
	  // margin-bottom: calc( var(--keyboard-height)); 
	//  bottom: 0;
	  position: absolute; /* 绝对定位 */
	    
	  height: 200rpx;
     width: 100%;
      display: flex;
      flex-direction: column;
      padding: 20px;
     background-color: white;
    
    .link-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
    padding-bottom: 20rpx;
  	.left, .center, .right {
  	  flex: 1;
  	  text-align: center;
  	}
  	.left {
  	margin-left: 20rpx;
  	 text-align: left; /* 左侧文本左对齐 */
  	}
  	
  	.right {
  	    margin-right: 20rpx;
  	    text-align: right; /* 右侧文本右对齐 */
  	}
    }
    .link-input {
  	padding-top: 20rpx;
      display: flex;
      flex-direction: column;
      .link-text, .link-url {
  	 height: 50rpx;
	// box-sizing: border-box;
        margin: 0 20rpx 20rpx 20rpx;
        padding-left: 8rpx;
        border: 1rpx solid #ccc;
        border-radius: 15rpx;
      }
    
    }
  }
}
</style>